import { Models } from '@/common/typings/modle'
import { Buffer, HttpException } from '@/core/HttpException'
import ExcelJs from 'exceljs'
import fs from 'fs'
import path from 'path'

const commonExport = (options: any) => async (ctx: Models.Ctx) => {
  const result = await options.getResult(ctx)
  if (result.length) {
    // 生成 excel
    const workbook = new ExcelJs.Workbook()
    const worksheet = workbook.addWorksheet(options.sheetName || options.fileName)
    worksheet.columns = options.excelColumns
    result.forEach((item: any) => {
      worksheet.addRow(item)
    })
    const fileName = `${options.fileName}.xlsx`
    const filePath = path.resolve(__dirname, fileName)
    try {
      fs.unlinkSync(filePath)
    } catch (e) {}
    await workbook.xlsx.writeFile(filePath)
    // todo 读取文件 并以流的形式返回
    const stream = fs.createReadStream(filePath)
    // 流返回后将文件删除
    setTimeout(() => {
      try {
        fs.unlinkSync(filePath)
      } catch (e) {}
    })
    throw new Buffer({ data: stream })
  }
  throw new HttpException({ msg: '没有要导出的数据' })
}
export default commonExport
